import Layouts from '@/components/Layout';
import React, { useEffect, useRef, useState } from 'react';
import './index.less';
import { Typography, Tabs, Button, Pagination, Empty, Spin } from 'antd';
import Activity from '@/components/Activity';
import Tour from '@/components/Tour';
import { useParams, history } from 'umi';
import { getCityDetail } from '@/service/api/location';
import { CitiesList } from '@/types/loaction';
import configs from '../../../../config/env';
import { ActivityList, ActivitySearch, TourList, TourSearch } from '@/types/touractivity';
import { getActivityList, getTourList } from '@/service/api/touractivity';
const CitiesDetail: React.FC = () => {
  const params: { cname: string } = useParams();
  const firstUpload = useRef(true); // 记录是否是首次加载页面
  const [cityInfo, setCityInfo] = useState<CitiesList | null>(null);
  const [tourlistLoading, setTourListLoading] = useState<boolean>(false);
  const [tourList, setTourList] = useState<TourList[]>([]);
  const [tourSearchQuery, setTourSearchQuery] = useState<TourSearch>({
    pageNum: 1,
    pageSize: 9,
    city: params.cname,
  });
  const [tourTotal, setTourTotal] = useState<number>(0);
  const [actListLoading, setActListLoading] = useState<boolean>(false);
  const [actList, setActList] = useState<ActivityList[]>([]);
  const [actListTotal, setActListTotal] = useState<number>(0);
  const [searchActQuery, setSearchActQuery] = useState<ActivitySearch>({
    pageNum: 1,
    pageSize: 9,
    city: params.cname,
  });
  const [key, setKey] = useState<string>('other_tour');
  const onChange2 = (key: string) => {
    console.log(key);
    setKey(key);
    if (key === 'other_tour') {
      setTourSearchQuery((tour) => ({ ...tour, pageNum: 1 }));
    } else {
      setSearchActQuery((act) => ({ ...act, pageNum: 1 }));
    }
  };
  const getCityDetailInfo = async () => {
    const { data }: { data: CitiesList } = await getCityDetail({
      cname: params.cname,
    });
    if (data) {
      setCityInfo(data);
    } else {
      history.push('/404');
    }
  };
  const getTourListByCityData = async () => {
    try {
      setTourListLoading(true);
      const { rows, total }: { rows: TourList[]; total: number } = await getTourList(
        tourSearchQuery,
      );
      setTourList(rows);
      setTourTotal(total);
    } finally {
      setTourListLoading(false);
    }
  };
  const handleChangePageTour = (page: number, pageSize: number) => {
    setTourSearchQuery({
      pageNum: page,
      pageSize,
      city: params.cname,
    });
  };
  const getActivityListDataByCity = async () => {
    try {
      setActListLoading(true);
      const { rows, total }: { rows: ActivityList[]; total: number } = await getActivityList(
        searchActQuery,
      );
      setActList(rows);
      setActListTotal(total);
    } finally {
      setActListLoading(false);
    }
  };
  const handleChangePageAct = (page: number, pageSize: number) => {
    setSearchActQuery({
      pageNum: page,
      pageSize,
      city: params.cname,
    });
  };
  useEffect(() => {
    getCityDetailInfo();
  }, []);
  useEffect(() => {
    getTourListByCityData();
  }, [tourSearchQuery]);
  useEffect(() => {
    if (firstUpload.current) {
      // 首次加载不执行
      firstUpload.current = false;
      return;
    }
    getActivityListDataByCity();
  }, [searchActQuery]);
  return (
    <Layouts>
      <div className="countries_detail_wrapper">
        <Typography.Title level={1}>{cityInfo?.cname}</Typography.Title>
        <div className="countries_main">
          <div className="left_intro_images">
            <div className="top_image">
              <img
                src={
                  cityInfo?.imgUrl
                    ? configs[process.env.API_ENV as any].API_SERVER + cityInfo?.imgUrl
                    : '/images/brazil.jpg'
                }
                alt=""
              />
            </div>
          </div>
          <div className="right_tab_wrapper">
            <Tabs
              defaultActiveKey="1"
              items={[
                {
                  label: `简介`,
                  key: '1',
                  children: (
                    <div className="intro_panel">
                      {cityInfo?.remark ?? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    </div>
                  ),
                },
                {
                  label: `文化`,
                  key: '2',
                  children: (
                    <div className="intro_panel">
                      {cityInfo?.culture ?? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    </div>
                  ),
                },
                {
                  label: `食物`,
                  key: '3',
                  children: (
                    <div className="intro_panel">
                      {cityInfo?.food ?? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    </div>
                  ),
                },
                {
                  label: `生活`,
                  key: '4',
                  children: (
                    <div className="intro_panel">
                      {cityInfo?.life ?? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    </div>
                  ),
                },
              ]}
            />
          </div>
        </div>
        <div className="other_info_wrpper">
          <div className="btn_wrap">
            {key === 'other_tour' ? (
              <Button
                type="primary"
                onClick={() => {
                  history.push('/hold?tab=tour');
                }}
              >
                举办探险
              </Button>
            ) : (
              <Button
                type="primary"
                ghost
                onClick={() => {
                  history.push('/hold?tab=share');
                }}
              >
                提交活动
              </Button>
            )}
          </div>
          <Tabs
            defaultActiveKey="other_tour"
            onChange={onChange2}
            items={[
              {
                label: `冒险`,
                key: 'other_tour',
                children: (
                  <div className="other_panel_wrppaer">
                    <p className="other_sub_tit">寻找当地旅游和导游来指导您的冒险之旅</p>
                    <Spin tip="正在玩命加载..." size="large" spinning={tourlistLoading}>
                      <div className="other_data_wrap">
                        {tourList.map((item) => (
                          <Tour
                            key={item.id}
                            title={item.title}
                            id={item.id}
                            time={item.time}
                            price={item.price}
                            remark={item.remark}
                            userInfo={item.user}
                            bacImg={item.bacImg}
                            tags={item.tags}
                          />
                        ))}
                      </div>
                    </Spin>
                    <div className="pagination_wrapper">
                      {tourTotal !== 0 && (
                        <Pagination
                          current={tourSearchQuery.pageNum}
                          total={tourTotal}
                          showTitle
                          pageSize={tourSearchQuery.pageSize}
                          showSizeChanger={false}
                          onChange={handleChangePageTour}
                        />
                      )}
                      {!tourlistLoading && tourTotal === 0 && (
                        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                      )}
                    </div>
                  </div>
                ),
              },
              {
                label: `活动`,
                key: 'other_act',
                children: (
                  <div className="other_panel_wrppaer">
                    <p className="other_sub_tit">探索{params.cname}的独特活动</p>
                    <Spin tip="正在玩命加载..." size="large" spinning={actListLoading}>
                      <div className="other_data_wrap">
                        {actList.map((item) => (
                          <Activity
                            key={item.id}
                            id={item.id}
                            country={item.country}
                            remark={item.describes}
                            userInfo={item.user}
                            imgUrl={item.imgUrl}
                            title={item.title}
                            tags={item.tags}
                            city={item.city}
                          ></Activity>
                        ))}
                      </div>
                    </Spin>
                    <div className="pagination_wrapper">
                      {actListTotal !== 0 && (
                        <Pagination
                          current={searchActQuery.pageNum}
                          total={actListTotal}
                          showTitle
                          pageSize={searchActQuery.pageSize}
                          showSizeChanger={false}
                          onChange={handleChangePageAct}
                        />
                      )}
                      {!actListLoading && actListTotal === 0 && (
                        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                      )}
                    </div>
                  </div>
                ),
              },
            ]}
          />
        </div>
      </div>
    </Layouts>
  );
};
export default CitiesDetail;
